#pragma once

#include"Socket.hpp"
#include"Protocol.hpp"
#include<pthread.h>
#include<functional>

using func_t=std::function<void(Net_Work::Socket* sockp)>;

class TcpServer;
class ThreadData
{
public:
    ThreadData(TcpServer* tcp_this,Net_Work::Socket* sockp)
        :_this(tcp_this),_sockp(sockp)
    {}
public:
    TcpServer* _this;
    Net_Work::Socket* _sockp;
};

class TcpServer
{
public:
    TcpServer(uint16_t port,func_t handler_request)
        :_port(port),_listensockfd(new Net_Work::TcpSocket()),_handler_request(handler_request)
    {
        _listensockfd->BuildListenSocketMethod(_port,Net_Work::backlog);
    }

    static void* ThreadRun(void* args)
    {
        pthread_detach(pthread_self());//分离线程
        ThreadData *td=static_cast<ThreadData*>(args);//
        td->_this->_handler_request(td->_sockp);
        td->_sockp->CloseSockfd();
        delete td->_sockp;
        delete td;
        return nullptr;
    }

    ~TcpServer()
    {
        delete _listensockfd;
    }
    void Loop()
    {
        while(true)
        {
            std::string peerip;
            uint16_t peerport;
            Net_Work::Socket *newsock = _listensockfd->AcceptConnection(&peerip, &peerport);
            std::cout << "获取到一个连接: " << newsock->GetSocket() << " client info: " << peerip << ":" << peerport << std::endl;
            if(newsock==nullptr)continue;
            pthread_t tid;
            ThreadData *td=new ThreadData(this,newsock);
            pthread_create(&tid,nullptr,ThreadRun,td);
            
            
            // sleep(10);
            // newsock->CloseSockfd();
        }
    }
private:
    uint16_t _port;
    Net_Work::Socket* _listensockfd;
public:
    func_t _handler_request;
};
